<template>
  <div class="container">
    <!-- 面包屑 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item>头条上传</el-breadcrumb-item>
      <el-breadcrumb-item>
        <span class="u-cursor" @click="$router.back()">计划管理</span>
      </el-breadcrumb-item>
      <el-breadcrumb-item>{{ pageTitle }}计划</el-breadcrumb-item>
    </el-breadcrumb>
    <Container class="u-pb60">
      <el-form
        class="m-form--detail"
        label-width="160px"
        :model="pageData"
        :rules="pageRules"
        ref="pageForm"
      >
        <el-form-item size="small" label="创建类型">
          <el-radio-group v-model="pageData.createdType">
            <el-radio-button :label="0">默认</el-radio-button>
            <el-radio-button :label="1">SDPA</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <ContainerTitle>请选择投放账号</ContainerTitle>
        <el-form-item prop="mainAccount" size="small" label="头条账户">
          <el-select
            class="u-w350"
            placeholder="请选择头条账户(手动搜索+多选)"
            filterable
            :multiple="pageData.createdType == 0"
            v-model="pageData.mainAccount"
            @change="handleChangeMainAccount"
            @remove-tag="removeTag"
          >
            <el-option
              v-for="item in mainAccountOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <div v-if="pageData.createdType == 1">
          <el-form-item label="商品库" prop="goodsLibrary">
            <el-select
              filterable
              v-model="pageData.goodsLibrary"
              placeholder="请选择"
              @change="selectGoodsLibrary"
            >
              <el-option
                v-for="item in goodsLibraryOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item class="u-mt15" label="商品页数">
            <el-input-number
              v-model="pageData.goodsPageNum"
              :min="1"
              label="视频页数"
            ></el-input-number>
            <el-button type="primary" @click="searchGoodsLibrary" class="u-ml10"
              >确定</el-button
            >
          </el-form-item>
          <el-form-item class="u-mt15" label="商品" prop="goods" filterable>
            <el-select v-model="pageData.goods" placeholder="请选择" filterable>
              <el-option
                v-for="item in goodsOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </div>
        <!--         <el-form-item prop="subAccount" size="small" label="头条子账户：">
          <el-select
            class="u-w350"
            placeholder="请选择头条子账户"
            filterable
            v-model="pageData.subAccount"
            :disabled="pageData.mainAccount==''"
            @change="handleChangesubAccount"
          >
            <el-option
              v-for="item in subAccountOptions"
              :key="item.accountId"
              :label="item.accountName"
              :value="item.accountId"
            ></el-option>
          </el-select>
        </el-form-item>-->
        <ContainerTitle>创建广告组</ContainerTitle>
        <el-form-item>
          <el-radio-group v-model="pageData.chooseType">
            <el-radio-button :label="0">新增</el-radio-button>
            <el-radio-button :label="1">选择已有</el-radio-button>
            <!--  <el-radio-button :label="3">自定义</el-radio-button> -->
          </el-radio-group>
        </el-form-item>
        <el-form-item
          size="small"
          label="广告组名称"
          v-if="pageData.chooseType == 0"
          prop="advGroupName"
        >
          <el-input
            class="u-w350"
            placeholder="1-40个汉字"
            v-model="pageData.advGroupName"
            rows="5"
            maxlength="40"
          ></el-input>
        </el-form-item>
        <el-form-item
          size="small"
          label="广告组名称"
          v-if="pageData.chooseType == 1"
        >
          <el-form-item
            v-for="(item, index) in pageData.groupList"
            :key="index"
            :label="item.accountName"
            :label-width="'250px'"
            :prop="'groupList.' + index + '.groupName'"
            :rules="pageRules.groupName"
            class="u-mt15"
          >
            <el-select
              class="u-w350"
              placeholder="请选择广告组名称"
              filterable
              v-model="item.groupName"
              @change="selectGroupName"
            >
              <el-option
                v-for="items in item.optionList.list[0]"
                :key="items.campaign_id"
                :label="items.campaign_name"
                :value="items.campaign_id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form-item>
        <el-form-item size="small" label="推广目的">
          <div class="u-black">应用推广提升应用的下载、安装、激活、付费</div>
        </el-form-item>
        <el-form-item size="small" label="广告组预算">
          <div class="u-black">不限</div>
          <!-- {{pageData.budget}} -->
        </el-form-item>
        <ContainerTitle>创建广告计划</ContainerTitle>
        <el-form-item prop="advName" size="small" label="广告计划名称">
          <el-input
            class="u-w350"
            placeholder="1-45个汉字"
            v-model="pageData.advName"
            rows="5"
            maxlength="50"
          ></el-input>
        </el-form-item>
        <el-form-item size="small" label="投放范围">
          <!-- <div class="u-black">默认</div> -->
          <el-radio-group v-model="pageData.delivery_range">
            <el-radio-button label="DEFAULT">默认</el-radio-button>
            <el-radio-button label="UNION">只投放到资讯联盟</el-radio-button>
            <el-radio-button label="UNIVERSAL">通投智选</el-radio-button>
            <!--  <el-radio-button :label="3">自定义</el-radio-button> -->
          </el-radio-group>
        </el-form-item>
        <el-form-item size="small" label="下载方式">
          <div class="u-black">下载链接</div>
        </el-form-item>
        <el-form-item class="u-w500" label="下载链接">
          <el-radio-group v-model="pageData.downloadType">
            <el-radio-button :label="1">安卓下载链接</el-radio-button>
            <el-radio-button :label="2">ios下载链接</el-radio-button>
            <!--  <el-radio-button :label="3">自定义</el-radio-button> -->
          </el-radio-group>
          <div v-if="pageData.downloadType == 1">
            <!-- <div>
              http://appdownload.alicdn.com/publish/litetao_android/latest/litetao_android_1568972753339.apk
            </div> -->
            <el-checkbox v-model="pageData.isFirst"
              >优先从系统应用商店下载（请确保应用在应用商店内已上架)</el-checkbox
            >
            <div class="bg-purple-light text-info">
              勾选后，将优先跳转目标应用对应手机系统应用商店安装详情页，跳转失败则使用下载链接下载。
            </div>
          </div>
          <div v-if="pageData.downloadType == 2"></div>
          <!-- <el-tabs v-model="pageData.downloadUrl" type="card" @tab-click="changeDownloadUrl">
            <el-tab-pane label="安卓下载链接" name="first">
              
            </el-tab-pane>
            <el-tab-pane label="ios下载链接" name="second">

            </el-tab-pane>
            <el-tab-pane label="自定义" name="third">

            </el-tab-pane>
          </el-tabs>-->
        </el-form-item>
        <el-form-item label="下载链接填写方式">
          <el-radio-group v-model="pageData.download_url_type">
            <el-radio-button :label="0">自定义</el-radio-button>
            <el-radio-button :label="1">选择已有</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item class="u-w500" prop="downloadUrl">
          <el-input
            v-if="pageData.download_url_type == 0"
            class="u-w350"
            type="textarea"
            v-model="pageData.downloadUrl"
            placeholder="请填写下载链接"
          ></el-input>
          <el-select
            v-model="pageData.downloadUrl"
            placeholder="请选择下载链接"
            v-else
            class="u-w350"
            @change="selectDownloadUrl(pageData.downloadUrl)"
          >
            <el-option
              v-for="(item, dindex) in downloadUrlOptions"
              :key="dindex"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <!--  <el-form-item label="转化目标"></el-form-item> -->
        <el-form-item class="u-w500" label="应用包名">
          <el-input
            class="u-w350"
            type="textarea"
            v-model="pageData.packages"
            placeholder="请填写应用包名"
          ></el-input>
        </el-form-item>

        <ContainerTitle class="font-size-defult">用户定向</ContainerTitle>
        <el-form-item label="地域">
          <div class="u-black">不限</div>
          <!--           <el-cascader
            placeholder="请点击选择地址"
            :options="options"
            v-model="selectedOptions"
            @change="handleChange"
            clearable
          ></el-cascader>-->
        </el-form-item>
        <el-form-item label="年龄">
          <el-checkbox-group v-model="pageData.age" @change="changeAge">
            <el-checkbox-button
              v-for="(item, index) in pageData.ageOption"
              :label="item.value"
              :key="index"
              >{{ item.name }}</el-checkbox-button
            >
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="已安装用户">
          <el-radio-group v-model="pageData.hide_if_exists">
            <el-radio-button :label="0">不限</el-radio-button>
            <el-radio-button :label="1">过滤</el-radio-button>
            <el-radio-button :label="2">定向</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="自定义人群">
          <el-radio-group v-model="pageData.crowd">
            <!-- <el-radio-button :label="1">不限</el-radio-button> -->
            <el-radio-button :label="2">自定义</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="定向人群">
          <div class="u-black">307608982</div>
        </el-form-item>
        <el-form-item label="排除人群">
          <div class="u-black" v-if="pageData.downloadType == 1">311092739</div>
          <div class="u-black" v-if="pageData.downloadType == 2">308132361</div>
        </el-form-item>
        <el-form-item label="智能放量">
          <div class="u-black">不启用</div>
        </el-form-item>
        <ContainerTitle class="font-size-defult">出价与预算</ContainerTitle>
        <el-form-item label="投放场景">
          <el-radio-group v-model="pageData.scene" @change="chageScene">
            <el-radio-button :label="0">常规投放</el-radio-button>
            <el-radio-button :label="1">放量投放</el-radio-button>
          </el-radio-group>
          <div v-if="pageData.scene == 1">
            <!--             <el-radio v-model="pageData.yxzh">通过学习期后，尝试优化转化成本</el-radio> -->
            <el-checkbox v-model="pageData.yxzh" @change="selectConversion"
              >通过学习期后，尝试优化转化成本</el-checkbox
            >
          </div>
        </el-form-item>
        <el-form-item label="竞价策略" v-if="pageData.scene == 0">
          <el-radio-group v-model="pageData.flow_control_mode">
            <el-radio-button :label="'FLOW_CONTROL_MODE_FAST'"
              >优先跑量</el-radio-button
            >
            <el-radio-button :label="'FLOW_CONTROL_MODE_SMOOTH'"
              >优先低成本</el-radio-button
            >
            <el-radio-button :label="'FLOW_CONTROL_MODE_BALANCE'"
              >均衡投放</el-radio-button
            >
          </el-radio-group>
          <div class="bg-purple-light text-info u-mt15">
            尽可能的将广告投放出去，可能会在较短的时间内消耗完预算，也会因为竞争环境的变化导致预算消耗出现较大的波动
          </div>
        </el-form-item>
        <el-form-item label="预算类型" prop="budgetAmount">
          <el-radio-group v-model="pageData.budget_mode">
            <el-radio-button :label="'BUDGET_MODE_DAY'">日预算</el-radio-button>
            <el-radio-button
              :label="'BUDGET_MODE_TOTAL'"
              v-if="pageData.scene !== 1"
              >总预算</el-radio-button
            >
          </el-radio-group>
          <div class="u-mt15">
            <el-input
              class="u-w350"
              placeholder="请输入预算"
              v-model="pageData.budgetAmount"
              rows="5"
              onkeyup="this.value = this.value.replace(/[^\d.]/g,'')"
              maxlength="200"
            ></el-input>
          </div>
        </el-form-item>
        <el-form-item>
          <div class="bg-purple-light text-info u-mt15">
            <div>
              1、日预算范围（单位元）
              <div>①出价方式为CPC、CPM、CPV时，日预算需大于100元</div>
              <div>②出价方式为OCPM、OCPC时，日预算需大于300元</div>
            </div>
            <div>
              2、总预算范围（单位元））
              <div>
                总预算：设了起始日期，将要求您预算设置需要大于或等于[投放天数 *
                100]，即满足每日最低预算300的要求
              </div>
            </div>
            <div>
              <div>3、单次预算修改幅度不小于100元</div>
              <div>4、日修改预算不超过20次</div>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="投放时间">
          <!--  <div class="u-black">从今天开始长期投放</div> -->
          <el-radio-group
            v-model="pageData.launchDateType"
            @change="changeDateType"
          >
            <el-radio-button :label="1">从今天开始长期投放</el-radio-button>
            <el-radio-button :label="2">选择投放时间</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="投放时间" v-if="pageData.launchDateType == 2">
          <el-date-picker
            class="u-w330"
            v-model="dateValue"
            size="mini"
            type="daterange"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="dateChange"
            format="yyyy/MM/dd"
            :picker-options="$store.state.PICKER_OPTIONS"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="投放时段">
          <el-radio-group v-model="pageData.launchPeriodType">
            <el-radio-button :label="1">不限</el-radio-button>
            <el-radio-button :label="2">指定时段</el-radio-button>
          </el-radio-group>
          <DropTime
            v-show="pageData.launchPeriodType === 2"
            :disabled="['detail'].indexOf(pageAction) !== -1"
            :value.sync="pageData.launchPeriod"
            @change="scheduleWeekChange"
            class="u-mt10"
          ></DropTime>
        </el-form-item>
        <el-form-item label="付费方式">
          <div class="u-black">OCPM</div>
        </el-form-item>
        <div
          v-for="(item, index) in pageData.conversionList"
          :key="index"
          class="u-mt15"
          style="border-bottom: 1px solid #eeeeee"
        >
          <el-form-item label="调整自动出价" v-if="pageData.scene == 1">
            <el-checkbox v-model="item.isAuto"
              >是否手动调整自动出价</el-checkbox
            >
            <el-button
              size="medium"
              type="primary"
              style="margin-left: 10px"
              @click="addConversionb(index)"
              v-if="pageData.scene == 1"
              >添加</el-button
            >
            <el-button
              size="medium"
              style="margin-left: 10px"
              @click="deleteConversionb(index)"
              v-if="pageData.scene == 1 && index !== 0"
              >删除</el-button
            >
          </el-form-item>
          <el-form-item
            label="目标转化出价(元)"
            :prop="'conversionList.' + index + '.targetconversionbid'"
            :rules="pageRules.targetconversionbid"
            v-if="pageData.scene == 0"
          >
            <el-input
              class="u-w350"
              placeholder="请输入目标转化出价"
              v-model="item.targetconversionbid"
              rows="5"
              maxlength="200"
              onkeyup="this.value = this.value.replace(/[^\d.]/g,'')"
              @blur="calculationRate(index)"
            ></el-input>
            <el-button
              size="medium"
              type="primary"
              style="margin-left: 10px"
              @click="addConversionb(index)"
              >添加</el-button
            >
            <el-button
              size="medium"
              style="margin-left: 10px"
              @click="deleteConversionb(index)"
              v-if="index !== 0"
              >删除</el-button
            >
          </el-form-item>
          <el-form-item
            label="目标转化出价(元)"
            :prop="'conversionList.' + index + '.targetconversionbid'"
            :rules="pageRules.targetconversionbid"
            v-if="pageData.scene == 1 && item.isAuto"
          >
            <el-input
              class="u-w350"
              placeholder="请输入目标转化出价"
              v-model="item.targetconversionbid"
              rows="5"
              maxlength="200"
              onkeyup="this.value = this.value.replace(/[^\d.]/g,'')"
              @blur="calculationRate(index)"
            ></el-input>
            <el-button
              size="medium"
              type="primary"
              style="margin-left: 10px"
              @click="addConversionb(index)"
              v-if="pageData.scene == 0"
              >添加</el-button
            >
            <el-button
              size="medium"
              style="margin-left: 10px"
              @click="deleteConversionb(index)"
              v-if="pageData.scene == 0 && index !== 0"
              >删除</el-button
            >
          </el-form-item>
          <el-form-item>
            <div class="bg-purple-light text-info">
              出价范围（单位元）：【CPC ：0.2-100】【CPM ：4-100】【CPV
              ：0.07-100】【OCPM、OCPC(穿山甲)、CPA：0.1-1000】
            </div>
          </el-form-item>
          <el-form-item label="深度优化方式">
            <!-- <div class="u-black">自定义双出价</div> -->
            <el-radio-group v-model="item.deep_bid_type">
              <el-radio-button :label="'SMARTBID'">自动优化</el-radio-button>
              <el-radio-button :label="'AUTO_MIN_SECOND_STAGE'"
                >自定义双出价</el-radio-button
              >
            </el-radio-group>
            <div
              v-if="
                item.deep_bid_type == 'AUTO_MIN_SECOND_STAGE' &&
                pageData.scene == 1
              "
            >
              <el-checkbox v-model="item.adjust_deep_cpa"
                >我的预算成本不在此范围内，我需要在此基础上进行调整</el-checkbox
              >
            </div>
          </el-form-item>
          <el-form-item
            label="深度转化出价"
            :prop="'conversionList.' + index + '.deepconversionbid'"
            :rules="pageRules.deepconversionbid"
            v-if="pageData.scene == 0"
          >
            <el-input
              class="u-w350"
              placeholder="请输入深度转化出价"
              v-model="item.deepconversionbid"
              rows="5"
              maxlength="200"
              onkeyup="this.value = this.value.replace(/[^\d.]/g,'')"
              @blur="calculationRate(index)"
            ></el-input>
            <div class="u-mt15">深度转化率={{ item.deepconversionrate }}%</div>
          </el-form-item>
          <el-form-item
            label="深度转化出价"
            :prop="'conversionList.' + index + '.deepconversionbid'"
            :rules="pageRules.deepconversionbid"
            v-if="pageData.scene == 1 && item.adjust_deep_cpa"
          >
            <el-input
              class="u-w350"
              placeholder="请输入深度转化出价"
              v-model="item.deepconversionbid"
              rows="5"
              maxlength="200"
              onkeyup="this.value = this.value.replace(/[^\d.]/g,'')"
              @blur="calculationRate(index)"
            ></el-input>
            <div class="u-mt15">深度转化率={{ item.deepconversionrate }}%</div>
          </el-form-item>
        </div>
        <ContainerTitle>创建广告创意</ContainerTitle>
        <!--  <el-form-item prop="AdvProgramName" size="small" label="广告创意名称">
          <el-input
            maxlength="50"
            class="u-w350"
            placeholder="1-20汉字"
            v-model="pageData.AdvProgramName"
          ></el-input>
        </el-form-item>-->
        <el-form-item label="广告位置">
          <el-radio-group
            v-model="pageData.advPosition"
            @change="changeAdvPosition"
          >
            <el-radio-button :label="1">优选广告位</el-radio-button>
            <el-radio-button :label="0">按媒体指定位置</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item>
          <el-checkbox-group
            v-model="pageData.inventory_type"
            v-if="pageData.advPosition == 0"
            class="u-mt15"
            @change="changeinventoryType"
          >
            <el-checkbox label="INVENTORY_FEED">今日头条</el-checkbox>
            <el-checkbox label="INVENTORY_VIDEO_FEED">西瓜视频</el-checkbox>
            <el-checkbox label="INVENTORY_HOTSOON_FEED">抖音火山版</el-checkbox>
            <el-checkbox label="INVENTORY_AWEME_FEED">抖音</el-checkbox>
            <el-checkbox label="INVENTORY_UNION_SLOT">穿山甲</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item>
          <!-- <div class="u-black">优选广告位</div> -->
          <div class="bg-purple-light text-info u-mt15">
            系统将根据您设置的定向，选择预估效果最好的广告位进行投放，并触达尽可能多的目标用户
          </div>
        </el-form-item>
        <el-form-item size="small" label="素材类型">
          <div class="u-black">竖版视频</div>
        </el-form-item>
        <el-form-item label="创意类型">
          <el-radio-group v-model="pageData.creativeType">
            <el-radio-button :label="1">自定义</el-radio-button>
            <el-radio-button :label="2">程序化</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="解析视频信息">
          <el-input
            type="textarea"
            class="u-w500"
            :rows="15"
            placeholder=""
            v-model="copyVideoInfo"
          ></el-input>
          <el-button
            type="primary"
            style="margin-left: 10px"
            @click="analysisVideo(copyVideoInfo)"
            >解析视频</el-button
          >
        </el-form-item>
        <el-form-item
          prop="videoFileList"
          size="small"
          label="视频："
          ref="creativeUploadVideo"
        >
          <div v-if="pageData.videoFileList.length > 0" class="u-mt15 u-mr10">
            <div
              v-for="(item, index) in pageData.videoFileList"
              :key="index"
              class="video-content"
            >
              <video
                :src="item.videoUrl"
                controls="controls"
                class="u-mr10"
                id="avatar"
              ></video>
              <i
                class="el-icon-close video-icon"
                @click="deleteVideoList(index)"
              ></i>
              <div class="video-name">{{ item.fileName }}</div>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="创意标题" :rules="pageRules.creativeTitle">
          <!-- <el-input  
          class="u-w350"
          v-model="pageData.slogan"
          maxlength="30"
          ></el-input>-->
          <el-input
            type="textarea"
            class="u-w500"
            :rows="15"
            placeholder="以回车换行，每个标题1-30个汉字"
            v-model="pageData.creativeTitle"
          ></el-input>
          <el-button
            type="primary"
            style="margin-left: 10px"
            @click="generateCreativeTitle"
            >生成标题</el-button
          >
        </el-form-item>
        <el-form-item>
          <div
            v-for="(points, index) in pageData.creative_title"
            :key="index"
            class="u-mt15"
          >
            <el-input
              class="u-w500"
              placeholder="长度1-30个汉字"
              :value="points"
              :disabled="true"
            ></el-input>
            <el-button
              style="margin-left: 10px"
              @click="deleteCreativeTitle(index)"
              >删除</el-button
            >
          </div>
        </el-form-item>
        <el-form-item label="应用下载详情页">
          <div class="u-black">选择已有</div>
          <div class="bg-purple-light text-info u-mt15 u-w500">
            用户点击广告中“立即下载”按钮以外的区域时所到达的页面
          </div>
        </el-form-item>
        <el-form-item label="行动号召按钮" prop="calltoAction">
          <el-select
            class="u-w350"
            placeholder="立即下载【默认+单选】"
            filterable
            v-model="pageData.calltoAction"
            @change="handleChangecalltoActionOptions"
          >
            <el-option
              v-for="item in calltoActionOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="应用名" prop="applicationName">
          <el-input
            class="u-w350"
            placeholder="1-10个汉字"
            v-model="pageData.applicationName"
            maxlength="10"
          ></el-input>
        </el-form-item>
        <el-form-item label="副标题">
          <el-input
            class="u-w350"
            placeholder="1-12个汉字"
            v-model="pageData.subTitle"
            maxlength="12"
          ></el-input>
        </el-form-item>
        <el-form-item label="广告评论">
          <div class="u-black">关闭</div>
        </el-form-item>
        <el-form-item label="创意展现">
          <div class="u-black">优选模式</div>
          <div class="bg-purple-light text-info u-mt15">
            选择优选模式，系统会自动对效果好的创意进行展示量倾斜，创意效果越好展示量越高
          </div>
        </el-form-item>
        <ContainerTitle>创意分类</ContainerTitle>
        <el-form-item label="创意分类" prop="industry">
          <el-cascader
            v-model="pageData.industry"
            :props="{ value: 'code' }"
            :options="industryOptions"
            @change="handleChangeIndustry"
            class="u-w350"
          ></el-cascader>
        </el-form-item>
        <el-form-item
          size="small"
          label="创意标签"
          :rules="pageRules.creativeLabel"
        >
          <div v-for="(item, index) in pageData.creativeLabel" :key="index">
            <el-form-item
              size="small"
              label
              :prop="'creativeLabel.' + index + '.label'"
              :rules="pageRules.creativeLabel"
            >
              <el-input
                class="u-w350"
                placeholder="1-20个汉字"
                v-model="item.label"
                :maxlength="index == 0 ? 5000 : 20"
                :disabled="index != 0"
              ></el-input>
              <el-button
                type="primary"
                style="margin-left: 10px"
                v-if="index == 0"
                @click="generateCreativeLabel"
                >生成标签</el-button
              >
              <el-button
                style="margin-left: 10px"
                v-else
                @click="deleteCreativeLabel(index)"
                >删除</el-button
              >
            </el-form-item>
          </div>
        </el-form-item>
        <ContainerTitle>创意监测</ContainerTitle>
        <el-form-item label="展示监测链接">
          <el-input
            class="u-w350"
            placeholder="输入监测链接"
            v-model="pageData.showMonitoringLinks"
            maxlength="500"
            type="textarea"
          ></el-input>
        </el-form-item>
        <el-form-item label="点击监测链接">
          <el-input
            class="u-w350"
            placeholder="输入监测链接"
            v-model="pageData.clickMonitoringLinks"
            maxlength="500"
            type="textarea"
          ></el-input>
        </el-form-item>
      </el-form>
      <el-dialog
        title="封面"
        :visible.sync="dialogVisibleImg"
        width="45%"
        :before-close="handleClose"
      >
        <div class="dialogCont">
          <div v-if="imgList.length > 0" class="dialogCont">
            <div
              v-for="(item, index) in imgList"
              :key="index"
              class="dialogImgCont"
              @click="handleClickChoose(item, index)"
            >
              <div class="imgList-icon">
                <img
                  v-if="!item.userCheck"
                  src="@/assets/img/checked.png"
                  alt
                />
                <img v-else src="@/assets/img/checked2.png" alt />
              </div>
              <img :src="item.url" alt class="imgList" />
            </div>
          </div>
          <!-- <div>内容为空</div> -->
        </div>

        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisibleImg = false">取 消</el-button>
          <el-button type="primary" @click="handleChooseSure">确 定</el-button>
        </span>
      </el-dialog>
    </Container>
    <Affix :offset-bottom="0">
      <ButtonGroup isFixed align="right">
        <el-button size="small" @click="$router.back()">返回</el-button>
        <el-button size="small" type="primary" @click="handleEnsure"
          >确定</el-button
        >
      </ButtonGroup>
    </Affix>
  </div>
</template>

<script>
import ContainerTitle from "@/components/container-title";
import Container from "@/components/container";
import Affix from "@/components/affix";
import ButtonGroup from "@/components/button-group";
import { ADV_ADRESS, BTN_TEXT, MAEKETOPTIONS } from "@/assets/js/flow-option";
import putArea from "@/assets/js/city";
import DropTime from "./components/drop-time";
import DATERANGE_OPTIONS, {
  DATERANGE_DISABLED_BEFORE,
} from "@/assets/js/daterange-option";
const validateMoney = (rule, value, callback) => {
  var patrn = /^\d+(\.\d+)?$/;
  if (value == "") {
    callback(new Error("请输入出价"));
  } else if (value.indexOf(".") != -1 && value.split(".")[1].length > 2) {
    callback(new Error("最多输入两位小数点")); //小数点后两位
  } else if (!patrn.exec(value)) {
    callback(new Error("请您输入数字")); //防止输入多个小数点
  } else {
    callback();
  }
};
export default {
  components: {
    ContainerTitle,
    Container,
    Affix,
    ButtonGroup,
    DropTime,
  },
  data() {
    return {
      DATERANGE_DISABLED_BEFORE,
      ADV_ADRESS,
      BTN_TEXT,
      MAEKETOPTIONS,
      pageAction: this.$route.query.action,
      BASE_URL: process.env.VUE_APP_BASE_URL,
      // 下拉
      platformOptions: [],
      customerOptions: [],
      productOptions: [],
      dialogVisibleImg: false,
      itemgroupName: [],
      account: [], //头条账户列表
      mainAccountOptions: [],
      goodsOptions: [], //商品下拉
      goodsLibraryOptions: [], //商品库下拉
      dateValue: "",
      copyVideoInfo: null, //复制的视频信息
      downloadUrlOptions: [], //下载链接选项
      calltoActionOptions: [
        {
          label: "立即下载",
          value: "BUTTON_TEXT_DOWNLOAD",
        },
        /*  {
          label: "去看看",
          value: "BUTTON_TEXT_LOOK",
        },
        {
          label: "去逛一逛",
          value: "BUTTON_TEXT_STROLL",
        },
        {
          label: "来拼一拼",
          value: "3",
        },
        {
          label: "立即抢购",
          value: "4",
        },
        {
          label: "立即下单",
          value: "5",
        },
        {
          label: "点击抢购",
          value: "6",
        },
        {
          label: "抢抢看",
          value: "7",
        },
        {
          label: "查看惊喜",
          value: "8",
        },
        {
          label: "了解详情",
          value: "9",
        },
        {
          label: "购买同款",
          value: "10",
        },
        {
          label: "获取优惠",
          value: "11",
        },
        {
          label: "领取好",
          value: "12",
        }, */
      ],
      subAccountOptions: [],
      value: [],
      productNameOptions: [],
      moudleNameOptions: [],
      chooseAppeOptions: [],
      crowdOptions: [],
      // CrowdOutOptions:[],
      advLocalOptions: [],
      btnTextOptions: [],
      industryOptions: [], //行业
      options: [],
      selectedOptions: [],
      cityArr: [], //城市列表
      areaArr: [], //区县列表
      province: "", //省
      city: "", //市
      area: "", // 区县,
      provinceCityArea: "", //选择器选择的省市区
      pageData: {
        download_url_type: 0, //下载链接填写方式
        goodsPageNum: 1, //商品页数
        goods: null, //商品
        goodsLibrary: null, //商品库
        createdType: 0, //创建类型 0默认 1SDPA
        delivery_range: "DEFAULT",
        deep_bid_type: "SMARTBID", //深度优化方式
        inventory_type: [], //指定媒体位置
        advPosition: 1, //广告位置
        industry: [], //行业
        creativeType: 1, //创意类型
        flow_control_mode: "FLOW_CONTROL_MODE_FAST", //竞价策略
        yxzh: false, //优先转化
        budget_mode: "BUDGET_MODE_DAY",
        mainAccount: null,
        calltoAction: "BUTTON_TEXT_DOWNLOAD", //行动号召选项
        applicationName: "淘宝特价版", //应用名
        subTitle: "省钱小技巧，来淘宝特价版", //副标题
        showMonitoringLinks: null, //展示监测链接
        clickMonitoringLinks: null, //点击监测链接
        subAccount: null,
        advName: null,
        market: null,
        budget: null,
        productName: null,
        advGroupName: null,
        moudleName: null,
        link: null,
        chooseApplication: null,
        firstDown: 0,
        phoneType: [],
        clickUrl: null,
        directionalCrowd: null,
        directionalCrowdOut: null,
        moudleCont: null,
        offerType: null,
        // years:[21,40],
        minYears: 18,
        maxYears: 55,
        putDate: null,
        cycleChoice: 0, // 投放周期
        cycleDaterange: [], // 投放周期时间段
        startTime: "", // 自定义投放周期
        endTime: "", // 自定义投放周期
        startDate: this.formatDateTime(new Date(), "y-m-d h-m"),
        endDate: "2099-01-01 00:00",
        scheduleChoice: 0, // 投放时段
        scheduleWeek: "", // 投放时段自定义
        downloadUrl: "", //下载链接
        chooseType: 0, //广告组方式
        downloadType: 1,
        isFirst: "",
        packages: null,
        budgetType: 1, //预算类型
        scene: 0, //投放场景
        age: ["AGE_BETWEEN_24_30"], //年龄
        ageOption: [
          { name: "24-30", value: "AGE_BETWEEN_24_30" },
          { name: "31-40", value: "AGE_BETWEEN_31_40" },
          { name: "41-49", value: "AGE_BETWEEN_41_49" },
          { name: "50+", value: "AGE_ABOVE_50" },
        ],
        groupList: [],
        hide_if_exists: 0, //过滤已安装
        budgetAmount: "", //预算金额
        launchDateType: 1, //投放时间类型
        launchPeriodType: 1, //投放时段类型
        launchPeriod: "", //投放时段
        conversionList: [
          {
            targetconversionbid: "", //目标转化出价 //出价和预算
            deepconversionbid: "", //深度转化出价
            deepconversionrate: 0, //深度转化率
            isAuto: "", //是否自动出价
            adjust_deep_cpa: "", //是否调整出价
            deep_bid_type: "SMARTBID",
          },
        ],
        crowd: 2, //定量人群
        priceArr: [
          {
            price: "",
          },
        ],
        AdvProgramName: null,
        advLocal: null,
        matterType: null,
        btnText: null,
        slogan: [
          {
            slogan: "",
          },
        ],
        creativeTitle: "",
        creative_title: [],
        creativeLabel: [
          {
            label: "",
          },
        ],
        fileList: [],
        videoSrc: null,
        videoFileList: [],
      },

      pageRules: {
        goodsLibrary: {
          required: true,
          message: "请选择商品库",
          trigger: ["blur", "change"],
        },
        goods: {
          required: true,
          message: "请选择商品",
          trigger: ["blur", "change"],
        },
        videoFileList: {
          required: true,
          message: "请解析需上传的视频",
          trigger: ["blur"],
        },
        inventory_type: {
          required: true,
          message: "请选择媒体指定位置",
          trigger: ["blur", "change"],
        },
        applicationName: {
          required: true,
          message: "请输入应用名",
          trigger: ["blur"],
        },
        creativeTitle: {
          min: 5,
          required: true,
          message: "请输入创意标题",
          trigger: ["blur"],
        },
        creativeLabel: {
          required: true,
          message: "请输入创意标签",
          trigger: ["blur"],
        },
        mainAccount: {
          required: true,
          message: "请选择头条账户",
          trigger: ["blur"],
        },
        calltoAction: {
          required: true,
          message: "请选择行动号召按钮",
          trigger: ["change", "blur"],
        },
        subAccount: {
          required: true,
          message: "请选择头条子账户",
          trigger: ["change", "blur"],
        },
        industry: {
          required: true,
          message: "请选择创意分类",
          trigger: ["change", "blur"],
        },
        advName: {
          required: true,
          message: "请输入广告计划名称",
          trigger: ["blur"],
        },
        downloadUrl: {
          required: true,
          message: "请输入下载链接",
          trigger: ["blur"],
        },
        productName: {
          required: true,
          message: "请选择产品名称",
          trigger: ["change", "blur"],
        },
        advGroupName: {
          required: true,
          message: "请输入广告组名称",
          trigger: ["blur"],
        },
        groupName: {
          required: true,
          message: "请选择广告组名称",
          trigger: ["blur"],
        },
        targetconversionbid: {
          required: true,
          /* message: "请输入目标转化出价", */
          trigger: ["blur"],
          validator: validateMoney,
        },
        deepconversionbid: {
          required: true,
          /*  message: "请输入深度转化出价", */
          trigger: ["blur"],
          validator: validateMoney,
        },
        budgetAmount: {
          required: true,
          message: "请输入预算",
          trigger: ["blur"],
        },
        moudleName: {
          required: true,
          message: "请选择定向模版文件名",
          trigger: ["change", "blur"],
        },
        price: [{ required: true, trigger: "blur", validator: validateMoney }],
        AdvProgramName: {
          required: true,
          message: "请输入广告创意名称",
          trigger: ["blur"],
        },
        advLocal: {
          required: true,
          message: "请选择广告位置",
          trigger: ["change", "blur"],
        },
        btnText: {
          required: true,
          message: "请选择行动号召按钮文案",
          trigger: ["change", "blur"],
        },
        slogan: {
          required: true,
          message: "不能为空",
          trigger: ["blur", "change"],
        },
        clickUrl: {
          required: true,
          message: "不能为空",
          trigger: ["blur"],
        },
        fileList: {
          required: true,
          message: "请上传封面图片",
          trigger: ["change", "blur"],
        },
        videoSrc: {
          required: true,
          message: "请上传视频",
          trigger: ["change", "blur"],
        },
      },

      //上传图片
      importUrl: "",
      dialogImageUrl: "",
      dialogVisible: false,
      importLoading: false,
      userCheck: false,
      imgList: [],
      arrImgList: [],
      // 上传视频
      videoFlag: false,
      videoUploadPercent: 0,
    };
  },
  computed: {
    pageTitle() {
      return {
        create: "新增",
        edit: "编辑",
        detail: "查看",
      }[this.pageAction];
    },
    sureParams() {
      // advertment:this.pageData.,
      let cover = [],
        video = [],
        creativeLabel = [],
        launchPeriodAry = [],
        flow_control_mode = "";
      creativeLabel = this.pageData.creativeLabel.filter(
        (item, index) => index > 0
      );
      let group = [],
        adjust_deep_cpa = [],
        adjustcpa = [];
      if (this.pageData.scene == 1) {
        if (this.pageData.yxzh == true) {
          flow_control_mode = "FLOW_CONTROL_MODE_BALANCE";
        } else {
          flow_control_mode = "FLOW_CONTROL_MODE_FAST";
        }
        this.pageData.conversionList.forEach((item) => {
          if (item.isAuto == false) {
            adjustcpa.push(0);
          } else {
            adjustcpa.push(1);
          }
        });
        this.pageData.conversionList.forEach((item) => {
          if (item.adjust_deep_cpa == false) {
            adjust_deep_cpa.push(0);
          } else {
            adjust_deep_cpa.push(1);
          }
        });
      } else {
        flow_control_mode = this.pageData.flow_control_mode;
      }
      if (this.pageData.chooseType == 0) {
        group = [
          {
            //广告组
            budget: 1000, //预算金额
            budget_mode: "BUDGET_MODE_INFINITE", //预算类型
            campaign_name: this.pageData.advGroupName, //广告组名称
            landing_type: "APP", //推广目的
          },
        ];
        if (this.pageData.advGroupName == null) {
          this.$message.error("请填写广告组名称");
          return;
        }
      } else {
        this.pageData.groupList.forEach((item) => {
          let obj = {
            account_id: item.accountId,
            campaign_id: item.groupName,
            budget: 1000,
            budget_mode: "BUDGET_MODE_INFINITE",
            landing_type: "APP",
          };
          group.push(obj);
        });
      }
      if (creativeLabel.length == 0) {
        this.$message.error("请生成创意标签");
        return;
      }
      if (this.pageData.age.length == 0) {
        this.$message.error("请选择年龄");
        return;
      }
      if (this.pageData.startDate == "" || this.pageData.endDate == "") {
        this.$message.error("请选择投放时间");
        return;
      }
      /*       if (this.pageData.advPosition == 0) {
        if (this.pageData.inventory_type.length == 0) {
          this.$message.error("请选择媒体指定位置");
          return;
        }
      } */
      if (this.pageData.launchPeriodType == 1) {
        for (let i = 0; i < 7 * 24; i++) {
          launchPeriodAry.push(0);
        }
        this.pageData.launchPeriod = launchPeriodAry.join();
      }
      this.pageData.videoFileList.forEach((item) => {
        let covers = [];
        item.covers.forEach((items) => {
          let obj = { material_toutiao_id: items.coverToutiaoId };
          if (items.coverToutiaoId != null) {
            covers.push(obj);
          }
        });
        video.push({
          material_toutiao_id: item.material_toutiao_id,
          covers: covers,
        });
      });
      let retargeting_tags_exclude, retargeting_tags_include;
      if (this.pageData.downloadType == 1) {
        retargeting_tags_include = [307608982];
        retargeting_tags_exclude = [311092739];
      } else if (this.pageData.downloadType == 2) {
        retargeting_tags_include = [307608982];
        retargeting_tags_exclude = [308132361];
      }
      return {
        account: this.account,
        sdpa: this.pageData.createdType == 0 ? false : true,
        productPlatformId: this.pageData.goodsLibrary,
        product_id: this.pageData.goods,
        cover: cover,
        creative: {
          //创建广告创意
          app_name: this.pageData.applicationName,
          smart_inventory: this.pageData.advPosition,
          action_track_url: this.pageData.clickMonitoringLinks, //点击监测链接
          ad_keywords: creativeLabel.map((item) => item.label), //创意标签
          creative_display_mode: "CREATIVE_DISPLAY_MODE_CTR", //创意展现方式
          inventory_type: this.pageData.inventory_type, //创意投放位置
          smart_inventory: 0, //是否使用优选广告位
          third_industry_id: this.pageData.industry[2], //创意分类
          title: this.pageData.creative_title, //创意标题
          track_url: this.pageData.showMonitoringLinks, //展示监测链接
          button_text: this.pageData.calltoAction, //行动号召
          advanced_creative_title: this.pageData.subTitle, //副标题
        },
        choose_already: this.pageData.chooseType,
        group: group,
        plan: {
          //广告计划
          creative_material_mode:
            this.pageData.creativeType == 1 ? "" : "STATIC_ASSEMBLE",
          age: this.pageData.age,
          hide_if_exists: this.pageData.hide_if_exists,
          app_type: this.pageData.downloadType == 1 ? "APP_ANDROID" : "APP_IOS", //计划应用下载类型
          bid: this.pageData.conversionList.map(
            (item) => item.targetconversionbid
          ), //目标转化出价
          budget_mode: this.pageData.budget_mode, //广告预算类型
          smart_bid_type:
            this.pageData.scene == 0
              ? "SMART_BID_CUSTOM"
              : "SMART_BID_CONSERVATIVE",
          deep_bid_type: this.pageData.conversionList.map(
            (item) => item.deep_bid_type
          ), //深度优化方式
          budget: this.pageData.budgetAmount,
          deep_cpabid: this.pageData.conversionList.map(
            (item) => item.deepconversionbid
          ), //深度转化出价
          adjust_cpa: adjustcpa,
          adjust_deep_cpa: adjust_deep_cpa,
          delivery_range: this.pageData.delivery_range, //投放范围
          download_mode:
            this.pageData.isFirst == true ? "APP_STORE_DELIVERY" : "DEFAULT", //下载模式
          download_type: "DOWNLOAD_URL", //	应用下载方式
          download_url: this.pageData.downloadUrl, //应用下载链接
          flow_control_mode: flow_control_mode, //广告投放速度类型
          hide_if_converted: "APP", //过滤已转化用户类型字段
          name: this.pageData.advName, //广告计划名称,
          operation: "disable", //计划状态
          packages: this.pageData.packages, //应用包名
          platform: this.pageData.downloadType == 1 ? "ANDROID" : "IOS", //受众平台
          pricing: "PRICING_OCPM", //计划出价类型
          /*  retargeting_tags_exclude: retargeting_tags_exclude, //排除人群包列表
          retargeting_tags_include: retargeting_tags_include, //定向人群包列表 */
          schedule_type:
            this.pageData.launchDateType == 1
              ? "SCHEDULE_FROM_NOW"
              : "SCHEDULE_START_END", //广告投放时间类型
          schedule_time: this.pageData.launchPeriod,
          start_time: this.pageData.startDate,
          end_time: this.pageData.endDate,
        },
        video: video,
      };
    },
  },
  methods: {
    selectDownloadUrl(download_url) {
      this.downloadUrlOptions.forEach((items) => {
        if (download_url == items.id) {
          this.pageData.packages = items.package;
        }
      });
    },
    getDownloadUrlList(agent, accountId) {
      this.$http({
        method: "get",
        url: "/marketing_tt/api/task_tt_general/get_downloadUrl_list",
        params: {
          agent: agent,
          accountId: accountId,
        },
      }).then((res) => {
        this.downloadUrlOptions = res.data.data;
        this.$forceUpdate();
      });
    },
    searchGoodsLibrary() {
      if (this.pageData.goodsLibrary == null) {
        this.$message.error("请选择商品库");
        return;
      }
      this.pageData.goods = null;
      this.$http({
        method: "get",
        url: "/marketing_tt/api/task_tt/get_product_list",
        params: {
          page: this.pageData.goodsPageNum,
          accountId: this.pageData.mainAccount,
          productPlatformId: this.pageData.goodsLibrary,
        },
      }).then((res) => {
        this.goodsOptions = res.data.data;
        this.$forceUpdate();
      });
    },
    selectGoodsLibrary() {
      this.pageData.goods = null;
      this.$http({
        method: "get",
        url: "/marketing_tt/api/task_tt/get_product_list",
        params: {
          page: this.pageData.goodsPageNum,
          accountId: this.pageData.mainAccount,
          productPlatformId: this.pageData.goodsLibrary,
        },
      }).then((res) => {
        this.goodsOptions = res.data.data;
        this.$forceUpdate();
      });
    },
    //删除视频
    deleteVideoList(index) {
      this.pageData.videoFileList.splice(index, 1);
    },
    //解析视频
    analysisVideo(data) {
      let copyVideoInfo = JSON.parse(data);
      console.log(copyVideoInfo);
      copyVideoInfo.forEach((item) => {
        let obj = {
          material_toutiao_id: item.materialToutiaoId,
          covers: item.covers,
          videoUrl: item.materialUrl,
          fileName: item.materialName,
        };
        this.pageData.videoFileList.push(obj);
      });
      console.log(this.pageData.videoFileList);
    },
    changeAdvPosition() {
      if (this.pageData.advPosition == 1) {
        this.pageData.inventory_type = [];
      }
    },
    changeinventoryType() {},
    handleChangeIndustry(value) {},
    selectConversion() {},
    // 递归判断列表，把最后的children设为undefined
    getTreeData(data) {
      for (var i = 0; i < data.length; i++) {
        if (data[i].children.length == 0) {
          // children若为空数组，则将children设为undefined
          data[i].children = undefined;
        } else {
          // children若不为空数组，则继续 递归调用 本方法
          this.getTreeData(data[i].children);
        }
      }
      return data;
    },
    getIndustry() {
      this.$http({
        method: "get",
        url: "/marketing_tt/api/task_tt/get_industry",
      }).then((res) => {
        let data = res.data.data.list;
        this.industryOptions = this.getTreeData(data);
      });
    },
    chageScene() {
      if (this.pageData.scene == 1) {
        this.pageData.budget_mode = "BUDGET_MODE_DAY";
      }
    },
    removeTag(val) {},
    selectGroupName() {
      /* this.pageData.groupList.forEach((item.index)=>{
        if()
      }) */
    },
    changeAge() {
      /*       this.pageData.age.forEach(item=>{
        if(item == "1"){
          if(this.pageData.age.length > 1 ){
            this.pageData.age.splice(this.pageData.age.indexOf("1"),1)
          }else{
            thia.pageData.age = ["1"]
          }
        }
      }) */
    },
    changeDateType() {
      if (this.pageData.launchDateType == 1) {
        this.pageData.startDate = this.formatDateTime(new Date(), "y-m-d h-m");
        this.pageData.endDate = "2099-01-01 00:00";
      } else {
        this.pageData.startDate = "";
        this.pageData.endDate = "";
      }
    },
    get_account_list() {
      this.$http({
        method: "get",
        url: "/marketing_tt/api/task_tt/get_account_list",
      }).then((res) => {
        this.mainAccountOptions = res.data.data;
      });
    },
    dateChange() {
      this.pageData.startDate = this.formatDateTime(
        this.dateValue[0],
        "y-m-d h-m"
      );
      this.pageData.endDate = this.formatDateTime(
        this.dateValue[1],
        "y-m-d h-m"
      );
    },
    initDistPicker() {
      let distData = putArea[0];
      let options = [];
      // 省
      for (var provinceKy in distData["100000"]) {
        let optProvinceItem = {
          value: provinceKy,
          label: distData["100000"][provinceKy],
        };
        if (distData[provinceKy]) {
          // 市
          for (var cityKy in distData[provinceKy]) {
            optProvinceItem.children = optProvinceItem.children
              ? optProvinceItem.children
              : [];
            let optCityItem = {
              value: cityKy,
              label: distData[provinceKy][cityKy],
            };
            if (distData[cityKy]) {
              // 区
              for (var areaKy in distData[cityKy]) {
                optCityItem.children = optCityItem.children
                  ? optCityItem.children
                  : [];
                let optAreaItem = {
                  value: areaKy,
                  label: distData[cityKy][areaKy],
                };
                optCityItem.children.push(optAreaItem);
              }
            }
            optProvinceItem.children.push(optCityItem);
          }
        }
        options.push(optProvinceItem);
      }
      self.distData = distData;
      self.options = options;
    },
    handleChange(value) {
      let self = this;
      //获取省名
      self.options.map((item, index) => {
        if (item.value == value[0]) {
          self.cityArr = item.children; //存储城市列表
          self.province = item.label;
        }
      });
      //获取市名
      self.cityArr.map((item, index) => {
        if (item.value == value[1]) {
          self.areaArr = item.children; //存储区县列表
          self.city = item.label;
        }
      });
      //获取区县名
      self.areaArr.map((item, index) => {
        if (item.value == value[2]) {
          self.area = item.label;
        }
      });
      self.provinceCityArea = self.province + self.city + self.area;
    },
    addConversionb(index) {
      this.pageData.conversionList.push({
        targetconversionbid: "", //目标转化出价 //出价和预算
        deepconversionbid: "", //深度转化出价
        deepconversionrate: 0, //深度转化率
        isAuto: "", //自动出价
        adjust_deep_cpa: "", //调整预期成本
        deep_bid_type: "SMARTBID",
      });
    },
    deleteConversionb(index) {
      this.pageData.conversionList.splice(index, 1);
    },
    addCreativeTitle() {
      if (this.pageData.creativeTitle.length >= 20) {
        return;
      }
      this.pageData.creativeTitle.push({
        title: "",
      });
    },
    deleteCreativeTitle(index) {
      this.pageData.creative_title.splice(index, 1);
    },
    /*  generateCreativeTitle() {
      let arr = this.pageData.creativeTitle[0].title.split(" ");
      if (arr.length > 10) {
        this.$message.error("最多生成10个创意");
      }
      arr.forEach((item) => {
        this.pageData.creativeTitle.push({ title: item });
      });
    }, */
    generateCreativeTitle() {
      let ary = this.pageData.creativeTitle.split(/[(\r\n)\r\n]+/);
      let err = 0;
      ary.forEach((item) => {
        let str = item
          .replace(/\s*/g, "")
          .replace(
            /[\ |\~|\`|\!|\@|\#|\$|\%|\^|\&|\*|\(|\)|\-|\_|\+|\=|\||\\|\[|\]|\{|\}|\;|\:|\"|\'|\,|\<|\.|\>|\/|\?|！|、|，|：|。]/g,
            ""
          );
        if (str.length > 30) {
          this.$message.error("每个标题最多30个汉字");
          err = 1;
        }
      });
      if (err == 1) {
        return;
      }
      this.pageData.creative_title = this.pageData.creative_title.concat(ary);
      console.log(this.pageData.creative_title);
    },
    addCreativeLabel() {
      if (this.pageData.creativeLabel.length >= 20) {
        return;
      }
      this.pageData.creativeLabel.push({
        label: "",
      });
    },
    generateCreativeLabel() {
      let sliceArr = this.pageData.creativeLabel.slice(0, 1);
      this.pageData.creativeLabel = sliceArr;
      let arr = this.pageData.creativeLabel[0].label.split(" ");
      if (arr.length > 20) {
        this.$message.error("最多生成20个创意标签");
        return;
      }
      arr.forEach((item) => {
        if (item.length > 10) {
          this.$message.error("每个创意标签最多10个字");
        } else {
          this.pageData.creativeLabel.push({ label: item });
        }
      });
    },
    deleteCreativeLabel(index) {
      this.pageData.creativeLabel.splice(index, 1);
    },
    calculationRate(index) {
      if (
        this.pageData.conversionList[index].targetconversionbid == "" ||
        this.pageData.conversionList[index].deepconversionbid == ""
      ) {
        return false;
      } else {
        let deepconversionrate =
          parseFloat(
            this.pageData.conversionList[index].targetconversionbid /
              this.pageData.conversionList[index].deepconversionbid
          ) * 100;
        this.pageData.conversionList[
          index
        ].deepconversionrate = deepconversionrate.toFixed(2);
      }
    },
    changeDownloadUrl() {},
    mapAccountName() {
      let value = this.subAccountOptions.find(
        (item) => item.accountId == this.pageData.subAccount
      );
      if (value) {
        return value.accountName;
      }
      return null;
    },
    mapMainAccountName() {
      let value = this.mainAccountOptions.find(
        (item) => item.accountId == this.pageData.mainAccount
      );
      if (value) {
        return value.accountName;
      }
      return null;
    },
    // 投放时段变更
    scheduleWeekChange() {
      /* this.$refs.pageForm.validateField("scheduleWeek"); */
    },
    videoBeforeUpload(file) {
      const isLt30MB = file.size / 1024 / 1024 < 100;
      const isSize = new Promise(function (resolve, reject) {
        let _URL = window.URL || window.webkitURL;
        let videoElement = document.createElement("video");
        // 当指定的音频/视频的元数据已加载时，会发生 loadedmetadata 事件。 元数据包括：时长、尺寸（仅视频）以及文本轨道。
        videoElement.addEventListener("loadedmetadata", function () {
          let width = videoElement.videoWidth;
          let height = videoElement.videoHeight;
          let duration = videoElement.duration; // 视频时长
          if (!isLt30MB)
            return this.$message.error("上传视频大小不能超过100MB！");
          if (Math.floor(duration) <= 4)
            return this.$message.error("上传视频时长不能小于4S！");
          resolve();
          /* let valid = `${width}*${height}` === "720*1280";
          valid ? resolve() : reject(); */
        });
        videoElement.src = _URL.createObjectURL(file);
      }).then(
        () => {
          return file;
        },
        () => {
          this.$message.error("上传视频尺寸为 720*1280！");
          return Promise.reject();
        }
      );
      return isSize;
    },
    uploadVideoProcess(event, file) {
      this.videoFlag = true;
      this.videoUploadPercent = file.percentage.toFixed(0) * 1;
    },
    handleSuccessVideo(res, file, fileList) {
      if (res.code == 1) {
        this.pageData.videoSrc = res.data[0];
        let obj = {
          coverUrl: res.data[0].coverUrl,
          videoUrl: res.data[0].videoUrl,
          fileName: file.name,
        };
        /*  this.pageData.videoFileList = fileList.map(
          item => item.response.data
        ); */
        /* this.pageData.videoFileList.push(res.data[0]); */
        this.pageData.videoFileList.push(obj);
        this.videoFlag = false;
      } else {
        this.$message.error(res.data.msg);
      }
    },
    handleSuccessImg(res) {
      if (res.code == 1) {
        let data = res.data[0];
        this.pageData.fileList.push(data);
      } else {
        this.$message.error(res.data.msg);
      }
    },
    handleRemoveVideo(file, fileList) {
      //this.pageData.videoSrc = fileList.map((item) => item.response.data[0]);
      //this.pageData.videoFileList = fileList.filter(item => !item.response);
      //this.pageData.videoFileList = fileList;
      // 停止上传
      let ary = [];
      if (fileList.length == 0) {
        this.pageData.videoFileList = [];
        this.pageData.videoSrc = null;
      } else {
        fileList.forEach((item) => {
          let obj = {
            coverUrl: item.response.data[0].coverUrl,
            videoUrl: item.response.data[0].videoUrl,
            fileName: item.name,
          };
          ary.push(obj);
        });
        this.pageData.videoFileList = ary;
      }
      this.uploadAbort("uploadVideo", file);
    },
    onChangeImg() {
      this.$refs["creativeUploadImg"].clearValidate();
    },
    onChangeVideo() {
      this.$refs["creativeUploadVideo"].clearValidate();
    },
    handleRemove(file, fileList) {
      this.pageData.fileList = fileList.map((item) => item.response.data[0]);
    },
    uploadAbort(ref, file) {
      this.$refs[ref].abort(file);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
        // return false
      } else if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
        // return false
      }

      const isSize = new Promise(function (resolve, reject) {
        let _URL = window.URL || window.webkitURL;
        let width = 720;
        let height = 1280;

        let img = new Image();
        img.onload = function () {
          if (!isJPG)
            if (!isLt2M)
              return this.$message.error("上传头像图片大小不能超过 2MB!");
          let valid = img.width == width && img.height == height;
          valid ? resolve() : reject();
        };
        img.src = _URL.createObjectURL(file);
      }).then(
        () => {
          return file;
        },
        () => {
          this.$message.error("请上传720*1280尺寸的图片!");
          return Promise.reject();
        }
      );
      return isJPG && isLt2M && isSize;
    },
    handleExceed(files, fileList) {
      this.$message.error(
        `当前限制选择 15 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
          files.length + fileList.length
        } 个文件`
      );
    },
    handleExceedVideo(files, fileList) {
      this.$message.error(
        `当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
          files.length + fileList.length
        } 个文件`
      );
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    // 下拉
    fetchPlatformOptions() {
      this.$http({
        method: "get",
        url: "/manage/api/bus/platform/get_platform",
        params: {
          status: 2,
          customerId: 0,
          productId: 0,
        },
      }).then((res) => {
        if (res.data.code === 1) {
          this.platformOptions = res.data.data;
        }
      });
    },
    mapOptionValue(data, id) {
      let item = data.find((item) => item.id === id);
      if (item) {
        return item.name;
      }
      return "-";
    },
    handleChangeCustomerOptions() {
      this.pageData.productId = null;
    },
    // 确定
    handleEnsure() {
      this.createDetail();
    },
    //添加
    handleClickAdd() {
      this.pageData.priceArr.push({
        price: "",
      });
    },
    // 删除
    handleClickRemove(index) {
      this.pageData.priceArr.splice(index, 1);
    },
    handleClickAddSlogan() {
      this.pageData.slogan.push({
        slogan: "",
      });
    },
    // 删除
    handleClickRemoveSlogan(index) {
      this.pageData.slogan.splice(index, 1);
    },
    // 新建
    createDetail() {
      if (this.pageData.creative_title.length == 0) {
        this.$message.error("请生成创意标题");
        return;
      }
      console.log(this.sureParams);
      this.$refs.pageForm.validate((valid) => {
        if (valid) {
          this.$http({
            method: "post",
            url: "/marketing_tt/api/task_tt/upload",
            data: this.sureParams,
          }).then((res) => {
            if (res.data.code === 1) {
              this.$message.success(res.data.msg);
              this.$router.back();
            } else {
              this.$message.error(res.data.msg);
            }
          });
        }
      });
    },
    // 详情
    getDetail() {
      this.$http({
        method: "get",
        url: "/manage/api/bus/account/get_by_id",
        params: {
          accountId: this.$route.query.id,
        },
      }).then((res) => {
        if (res.data.code === 1) {
          if (this.pageAction === "edit") {
            let {
              id,
              platformId,
              username,
              // accountName,
              password,
              accountId,
              usernameIdList,
              customerId,
              productId,
              remarks,
            } = res.data.data;
            this.pageData = {
              id,
              platformId,
              username,
              // accountName,
              password,
              accountId,
              usernameIdList,
              customerId,
              productId,
              remarks,
            };
          } else {
            this.pageData = res.data.data;
          }
        }
      });
    },
    // 根据子账号获取应用，人群
    handleChangesubAccount() {
      this.getCrowdList();
      if (this.pageData.market == 2 && this.pageData.subAccount) {
        this.getProductList();
      }
    },
    // 获取应用
    getProductList() {
      this.$http({
        method: "get",
        url: "/marketing_tt/api/task/getProductList",
        params: {
          accountId: this.pageData.subAccount,
        },
      }).then((res) => {
        if (res.data.code === 1) {
          this.chooseAppeOptions = res.data.data;
        } else {
          this.$message.error(res.data.msg);
        }
      });
    },
    // 获取人群
    getCrowdList() {
      this.$http({
        method: "get",
        url: "/marketing_tt/api/task/getCrowdList",
        params: {
          accountId: this.pageData.subAccount,
        },
      }).then((res) => {
        if (res.data.code === 1) {
          this.crowdOptions = res.data.data;
        } else {
          this.$message.error(res.data.msg);
        }
      });
    },
    // 根据主账号获取子账号
    handleChangeMainAccount() {
      let ary = [];
      let selectList = this.pageData.groupList;
      this.account = [];
      let mainAccount;
      let agent;
      if (typeof this.pageData.mainAccount == "number") {
        mainAccount = [this.pageData.mainAccount];
      } else {
        mainAccount = this.pageData.mainAccount;
      }

      this.mainAccountOptions.forEach((item) => {
        mainAccount.forEach((items, index) => {
          if (index == 0) {
            agent = item.agent;
          }
          if (item.id == items) {
            this.account.push({
              accountId: item.id,
              accountName: item.name,
              optionList: [],
              groupName: "",
              agent: item.agent,
            });

            this.$http({
              method: "get",
              url: "/marketing_tt/api/task_tt/get_campaign_list",
              params: {
                accountId: item.id,
              },
            }).then((res) => {
              if (res.data.code === 1) {
                this.account.forEach((aitem) => {
                  if (aitem.accountId == res.data.data.list[0][0].account_id) {
                    aitem.optionList = res.data.data;
                    aitem.groupName = "";
                  }
                });
                /* this.account[index].optionList = res.data.data;
                this.account[index].groupName = ""; */
                selectList.forEach((citems) => {
                  this.account.forEach((citem) => {
                    if (citems.accountId == citem.accountId) {
                      if (citems.groupName != "") {
                        citem.groupName = citems.groupName;
                      }
                    }
                  });
                });
              } else {
              }
            });
          }
        });
      });
      this.pageData.groupList = [...this.account];
      if (this.pageData.createdType == 1) {
        this.pageData.goodsLibrary = null;
        this.$http({
          method: "get",
          url: "/marketing_tt/api/task_tt/get_product_availables",
          params: {
            accountId: this.pageData.mainAccount,
          },
        }).then((res) => {
          this.goodsLibraryOptions = res.data.data;
          this.$forceUpdate();
        });
      }
      this.getDownloadUrlList(agent, mainAccount[0]);
    },
    handleChangecalltoActionOptions() {},
    // 根据模版获取模版数据
    handleChangeMoudleName() {
      this.$http({
        method: "get",
        url: "/marketing_tt/api/task/getTemplateByName",
        params: {
          name: this.pageData.moudleName,
        },
      }).then((res) => {
        if (res.data.code === 1) {
          this.pageData.moudleCont = res.data.data;
          // this.$set(this.pageData.moudleCont,data)
          // let data =
          //  = data
        } else {
          this.$message.error(res.data.msg);
        }
      });
    },
    // 获取主账号
    /*  getMainAccount() {
      this.$http({
        method: "get",
        url: "/marketing_tt/api/task/getAllMasterAccount",
      }).then((res) => {
        if (res.data.code === 1) {
          //this.mainAccountOptions = res.data.data;
        } else {
          this.$message.error(res.data.msg);
        }
      });
    }, */
    // 获取模版名称
    /*  getModuleData() {
      this.$http({
        method: "get",
        url: "/marketing_tt/api/task/getAllTemplate",
      }).then((res) => {
        if (res.data.code === 1) {
          this.moudleNameOptions = res.data.data;
        } else {
          this.$message.error(res.data.msg);
        }
      });
    }, */
    // 根据视频选取封面
    handleClickChoosePic() {
      // 图片弹出框+回显
      this.arrImgList = [];
      this.$http({
        method: "get",
        url: "/marketing_tt/api/task/video_intercept",
        params: {
          videoUrl: this.pageData.videoSrc.url,
        },
      }).then((res) => {
        if (res.data.code === 1) {
          this.dialogVisibleImg = true;
          this.imgList = res.data.data;
          for (let index = 0; index < this.imgList.length; index++) {
            this.$set(this.imgList[index], "userCheck", false);
          }
        } else {
          this.$message.error(res.data.msg);
        }
      });
    },
    handleClickChoose(e, index) {
      e.userCheck = !e.userCheck;
      let chooseImg = this.imgList[index];
      if (e.userCheck) {
        this.arrImgList.push(chooseImg);
      } else {
        let arrUrl = [chooseImg].map((item) => item.url);
        const result = this.arrImgList.filter(
          (item) => !arrUrl.includes(item.url)
        );
        this.arrImgList = result;
      }
    },
    handleChooseSure() {
      this.dialogVisibleImg = false;
      this.pageData.fileList = this.pageData.fileList.concat(this.arrImgList);
    },
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          done();
        })
        .catch((_) => {});
    },
  },
  created() {
    // this.getDetail();
    // 获取主账号
    this.getIndustry();
    this.get_account_list();
    /* this.getMainAccount(); */
    // 获取模版名称
    /* this.getModuleData(); */
    this.initDistPicker();
    // // 获取选择应用
    // this.getProductList()
    // // 获取定向人群
    // this.getCrowdList()
    // // 获取排除人群
    // this.getCrowdOutList()
    /**
     * 获取主帐号
     * 1.根据主账号获取子账号
     * 2.获取模版名称传String
     * 3.根据模版名称获取模版内容
     * 4.根据子账户获取应用，定向人群,
     * 4-1 Html 渲染应用，定向人群    +++++++++++++
     * 5.按钮文案写死传String
     * 6.上传视频，图片之后赋值
     * 7.添加对应字段           +++++++++++++++++
     *
     * 上传视频，图片，出价校验问题
     *
     *
     *
     * 定向人群。排除人群，选择应用，
     * 年龄，投放时间，营销目标，选择应用，优先应用商店下载，自定义，投放链接，定向人群，排除人群
     */
  },
};
</script>
<style scoped>
.el-icon-caret-right {
  transition: none !important;
}
.el-select__input {
  vertical-align: baseline !important;
}
.el-select--medium {
  vertical-align: bottom !important;
}
.title {
  margin-top: 20px;
}
.coumn {
  width: 400px;
}
.text-info {
  width: 650px;
  padding: 5px;
}
video {
  width: 148px;
  height: 148px;
}
.video-content {
  display: inline-block;
  position: relative;
  width: 200px;
  text-align: center;
}
.video-content .video-icon {
  position: absolute;
  right: 10px;
  top: 10px;
}
.video-content .video-name {
  height: 65px;
  overflow: hidden;
  font-size: 10px;
}
.tip {
  position: absolute;
  top: -55px;
  left: 520px;
  font-size: 12px;
}
.avatar-uploader .el-upload {
  border: 1px dashed #c0ccda;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  background-color: #fbfdff;
  width: 148px;
  height: 148px;
  line-height: 148px;
  text-align: center;
  border-radius: 6px;
}
.avatar {
  width: 148px;
  height: 148px;
  display: block;
}
.b50 {
  width: 55% !important;
}
.chooseApp {
  word-break: break-all;
}
.putDate {
  position: absolute;
  top: 0px;
  left: 360px;
}
.dialogCont {
  overflow: hidden;
}
.dialogImgCont {
  float: left;
  margin-right: 7px;
  margin-left: 8px;
  position: relative;
  width: 148px;
  height: 148px;
  margin-top: 15px;
}
.chooseImg {
  position: absolute;
  left: 200px;
  top: 80px;
}
.imgList {
  width: 148px;
  height: 148px;
}
.imgList-icon {
  position: absolute;
  right: 5px;
  top: 5px;
  font-size: 20px;
}
.imgList-icon img {
  width: 28px;
  height: 28px;
}
</style>
